<template>
  <div class="rejection-review-container">
    <!-- 页面标题与操作区 -->
    <div class="page-header">
      <h2>{{ currentView === 'list' ? '拒赔审核管理' : '拒赔详情审核' }}</h2>
      <div class="header-actions">
        <!-- 审核视图的返回按钮 -->
        <el-button
            v-if="currentView === 'review'"
            @click="switchToView('list')"
        >
          <el-icon><ArrowLeft /></el-icon>
          返回拒赔列表
        </el-button>
      </div>
    </div>

    <!-- 错误提示区域 -->
    <el-alert
        v-if="errorMsg"
        :message="errorMsg"
        type="error"
        show-icon
        closable
        @close="errorMsg = ''"
        style="margin-bottom: 16px"
    />

    <!-- 1. 拒赔列表视图（默认展示） -->
    <template v-if="currentView === 'list'">
      <!-- 筛选条件区 -->
      <el-card shadow="hover" class="filter-card">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <!-- 报案编号筛选 -->
          <el-form-item label="报案编号">
            <el-input
                v-model="filterForm.reportNo"
                placeholder="请输入报案编号"
                clearable
                style="width: 200px"
            />
          </el-form-item>

          <!-- 拒赔状态筛选 -->
          <el-form-item label="拒赔状态">
            <el-select
                v-model="filterForm.rejectStatus"
                placeholder="请选择拒赔状态"
                clearable
                style="width: 200px"
                @change="handleStatusChange"
            >
              <el-option label="待审核" value="1" />
              <el-option label="已拒赔" value="2" />
              <el-option label="审核未通过" value="3" />
            </el-select>
          </el-form-item>

          <!-- 筛选按钮 -->
          <el-form-item>
            <el-button type="primary" @click="getRejectionList">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 拒赔列表展示区 -->
      <el-card shadow="hover" class="list-card">
        <el-table
            :data="rejectionList"
            border
            stripe
            style="width: 100%"
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
            :loading="loading"
            @row-click="handleRowClick"
        >
          <!-- 拒赔ID -->
          <el-table-column label="拒赔ID" prop="rejectionId" width="180" />

          <!-- 报案编号（核心关联字段） -->
          <el-table-column label="报案编号" prop="reportNo" width="200" />

          <!-- 保单编号 -->
          <el-table-column label="保单编号" prop="policyId" width="180" />

          <!-- 立案/核赔号（有核赔ID则显示核赔号，否则显示立案号） -->
          <el-table-column label="关联编号" width="180">
            <template #default="scope">
              <span v-if="scope.row.preClaimId">核赔号：{{ scope.row.preClaimId }}</span>
              <span v-else>立案号：{{ scope.row.registrationId || '-' }}</span>
            </template>
          </el-table-column>

          <!-- 拒赔操作人员 -->
          <el-table-column label="拒赔操作员" width="140">
            <template #default="scope">
              {{ scope.row.operatorName || scope.row.userId || '-' }}
            </template>
          </el-table-column>

          <!-- 拒赔状态 -->
          <el-table-column label="拒赔状态" prop="rejectStatus" width="140">
            <template #default="scope">
              <el-tag
                  :type="rejectStatusMap[scope.row.rejectStatus]?.type"
                  :icon="rejectStatusMap[scope.row.rejectStatus]?.icon"
                  size="small"
              >
                {{ rejectStatusMap[scope.row.rejectStatus]?.text }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 拒赔申请时间 -->
          <el-table-column label="申请时间" width="200">
            <template #default="scope">
              {{ formatDateTime(scope.row.rejectTime) }}
            </template>
          </el-table-column>

          <!-- 操作按钮 -->
          <el-table-column label="操作" fixed="right" width="120">
            <template #default="scope">
              <el-button
                  type="primary"
                  size="small"
                  @click="toReviewPage(scope.row)"
                  :loading="scope.row.reviewLoading"
              >
                查看审核
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页控件 -->
        <div class="pagination" style="margin-top: 15px; text-align: right">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageNum"
              :page-sizes="[5, 10, 20, 50]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
          />
        </div>
      </el-card>
    </template>

    <!-- 2. 拒赔审核详情视图 -->
    <template v-if="currentView === 'review'">
      <el-card shadow="hover" class="main-card">
        <!-- 数据概览区域（折叠面板，关联多维度信息） -->
        <el-collapse
            class="info-collapse"
            v-model="activePanels"
            style="margin-bottom: 24px"
        >
          <!-- 拒赔基本信息（必展） -->
          <el-collapse-item title="拒赔基本信息" name="rejection" :disabled="!currentRejection.rejectionId">
            <el-descriptions column="2" border>
              <el-descriptions-item label="拒赔ID" :span="2" class="highlight-item">
                {{ currentRejection.rejectionId || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="报案编号">{{ currentRejection.reportNo || '-' }}</el-descriptions-item>
              <el-descriptions-item label="关联编号">
                <span v-if="currentRejection.preClaimId">核赔号：{{ currentRejection.preClaimId }}</span>
                <span v-else>立案号：{{ currentRejection.registrationId || '-' }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="保单编号">{{ currentRejection.policyId || '-' }}</el-descriptions-item>
              <el-descriptions-item label="拒赔申请时间">{{ formatDateTime(currentRejection.rejectTime) }}</el-descriptions-item>
              <el-descriptions-item label="拒赔操作员">{{ currentRejection.operatorName || currentRejection.userId || '-' }}</el-descriptions-item>
              <el-descriptions-item label="当前拒赔状态">
                <el-tag :type="rejectStatusMap[currentRejection.rejectStatus]?.type">
                  {{ rejectStatusMap[currentRejection.rejectStatus]?.text }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="拒赔原因" :span="2">{{ currentRejection.rejectReason || '-' }}</el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>

          <!-- 报案信息（通过报案号关联） -->
          <el-collapse-item title="报案信息" name="report" :disabled="!reportInfo.reportNo">
            <el-descriptions column="2" border>
              <el-descriptions-item label="报案编号" :span="2" class="highlight-item">
                {{ reportInfo.reportNo || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="报案人">{{ reportInfo.reporterName || '-' }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ reportInfo.reporterPhone || '-' }}</el-descriptions-item>
              <el-descriptions-item label="灾祸类型">{{ getDisasterType(reportInfo.disasterType) }}</el-descriptions-item>
              <el-descriptions-item label="灾祸发生时间">{{ formatDateTime(reportInfo.disasterOccurTime) }}</el-descriptions-item>
              <el-descriptions-item label="损失描述" :span="2">{{ reportInfo.lossDescription || '-' }}</el-descriptions-item>
              <el-descriptions-item label="农户预估损失(元)">{{ formatCurrency(reportInfo.lossEstimate) }}</el-descriptions-item>
              <el-descriptions-item label="报案状态">
                <el-tag :type="reportStatusMap[reportInfo.reportStatus]?.type">
                  {{ reportStatusMap[reportInfo.reportStatus]?.text }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>

          <!-- 保单信息（通过报案信息关联） -->
          <el-collapse-item title="保单信息" name="policy" :disabled="!policyInfo.policyId">
            <el-descriptions column="2" border>
              <el-descriptions-item label="保单编号" :span="2" class="highlight-item">
                {{ policyInfo.policyId || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="投保人ID">{{ policyInfo.insuredId || '-' }}</el-descriptions-item>
              <el-descriptions-item label="保险标的">{{ policyInfo.insuranceSubject || '-' }}</el-descriptions-item>
              <el-descriptions-item label="保险金额(元)">{{ formatCurrency(policyInfo.sumInsured) }}</el-descriptions-item>
              <el-descriptions-item label="保险期间">
                {{ formatDate(policyInfo.startDate) }} 至 {{ formatDate(policyInfo.endDate) }}
              </el-descriptions-item>
              <el-descriptions-item label="缴费状态">{{ getPayStatus(policyInfo.payStatus) }}</el-descriptions-item>
              <el-descriptions-item label="保单状态">{{ getPolicyStatus(policyInfo.policyStatus) }}</el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>

          <!-- 立案信息（有立案号则显示） -->
          <el-collapse-item title="立案信息" name="registration" :disabled="!currentRejection.registrationId">
            <el-descriptions column="2" border>
              <el-descriptions-item label="立案ID" :span="2" class="highlight-item">
                {{ registrationInfo.registrationId || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="关联报案号">{{ reportInfo.reportNo || '-' }}</el-descriptions-item>
              <el-descriptions-item label="立案日期">{{ formatDateTime(registrationInfo.registrationTime) }}</el-descriptions-item>
              <el-descriptions-item label="立案金额(元)">{{ formatCurrency(registrationInfo.surveyorLossEstimate) }}</el-descriptions-item>
              <el-descriptions-item label="责任认定">{{ getLiabilityType(registrationInfo.isCovered) }}</el-descriptions-item>
              <el-descriptions-item label="立案操作员">{{ registrationInfo.registrarId || '-' }}</el-descriptions-item>
              <el-descriptions-item label="立案备注" :span="2">{{ registrationInfo.remark || '-' }}</el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>

          <!-- 核赔信息（支持按报案号加载，无数据时显示重试按钮） -->
          <el-collapse-item title="核赔信息" name="verification" :disabled="!currentRejection.reportNo">
            <!-- 加载状态 -->
            <div v-if="verificationLoading" class="loading-state" style="text-align: center; padding: 20px;">
              <el-loading-spinner size="30" />
              <p style="margin-top: 10px;">正在加载核赔信息...</p>
            </div>
            <!-- 无数据状态（提供按报案号加载按钮） -->
            <div v-else-if="!hasVerificationData()" class="empty-state" style="padding: 30px; text-align: center;">
              <el-empty
                  image="https://element-plus.org/images/empty.svg"
                  description="未查询到核赔信息"
              >
                <el-button
                    type="primary"
                    size="small"
                    @click="fetchVerificationByReportNo(currentRejection.reportNo)"
                    :loading="verificationLoading"
                >
                  点击通过报案号加载
                </el-button>
              </el-empty>
            </div>
            <!-- 有数据状态 -->
            <el-descriptions v-else column="2" border>
              <el-descriptions-item label="核赔ID" :span="2" class="highlight-item">
                {{ verificationInfo.preClaimId || verificationInfo.verificationId || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="关联报案号">{{ verificationInfo.reportNo || currentRejection.reportNo || '-' }}</el-descriptions-item>
              <el-descriptions-item label="核赔金额(元)">{{ formatCurrency(verificationInfo.finalCompensation || verificationInfo.verificationAmount || 0) }}</el-descriptions-item>
              <el-descriptions-item label="核赔结论">{{ verificationInfo.verificationResult || verificationInfo.verificationOpinion || '-' }}</el-descriptions-item>
              <el-descriptions-item label="核赔操作员">{{ verificationInfo.verifierId || '-' }}</el-descriptions-item>
              <el-descriptions-item label="核赔时间">{{ formatDateTime(verificationInfo.verificationTime) }}</el-descriptions-item>
              <el-descriptions-item label="核赔备注" :span="2">{{ verificationInfo.verificationRemark || '-' }}</el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>
        </el-collapse>

        <!-- 审核表单（仅待审核状态可操作） -->
        <el-form
            ref="reviewFormRef"
            :model="reviewForm"
            label-width="160px"
            :rules="reviewRules"
            class="review-form"
            :disabled="currentRejection.rejectStatus !== 1 || submitLoading"
        >
          <!-- 审核人员信息 -->
          <el-form-item label="审核人员ID" prop="rejectExamineId" required>
            <el-select
                v-model="reviewForm.rejectExamineId"
                placeholder="请选择审核人员"
                clearable
                filterable
                style="width: 100%"
            >
              <el-option
                  v-for="staff in reviewerOptions"
                  :key="staff.workNo"
                  :label="`${staff.realName}（工号：${staff.workNo}）`"
                  :value="staff.workNo"
              />
            </el-select>
          </el-form-item>

          <!-- 审核结果（通过/不通过） -->
          <el-form-item label="审核结果" prop="rejectStatus" required>
            <el-radio-group v-model="reviewForm.rejectStatus" @change="handleReviewResultChange">
              <el-radio label="2">通过（确认拒赔）</el-radio>
              <el-radio label="3">不通过（驳回拒赔）</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 审核意见（必填） -->
          <el-form-item label="审核意见" prop="examineReason" required>
            <el-input
                v-model="reviewForm.examineReason"
                type="textarea"
                rows="4"
                placeholder="请详细说明审核意见（如：拒赔原因充分，同意拒赔；或：材料不全，驳回拒赔申请）"
            />
            <div class="el-form-item__help">
              <span class="text-warning">! 审核意见需详细准确，作为拒赔最终依据</span>
            </div>
          </el-form-item>

          <!-- 操作按钮（仅待审核状态显示） -->
          <el-form-item class="form-actions" v-if="currentRejection.rejectStatus === 1">
            <el-button @click="handleResetReview" :disabled="submitLoading">重置</el-button>
            <el-button
                type="primary"
                @click="handleSubmitReview"
                :loading="submitLoading"
            >
              提交审核结果
            </el-button>
          </el-form-item>

          <!-- 已审核状态提示（非待审核状态显示） -->
          <el-form-item v-else>
            <el-alert
                :title="`当前状态：${rejectStatusMap[currentRejection.rejectStatus]?.text}`"
                :type="rejectStatusMap[currentRejection.rejectStatus]?.type"
                show-icon
                style="width: 100%"
            >
              <template #desc>
                <div>
                  <p>审核人员：{{ currentRejection.rejectExamineName || currentRejection.rejectExamineId || '-' }}</p>
                  <p>审核意见：{{ currentRejection.examineReason || '-' }}</p>
                </div>
              </template>
            </el-alert>
          </el-form-item>
        </el-form>
      </el-card>
    </template>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import {
  CheckCircle,
  Warning,
  Close,
  ArrowLeft,
  Search
} from '@element-plus/icons-vue'
import axios from 'axios'
import hxxp from "@/utils/hxxp"; // 复用项目中已有的请求工具

// 路由实例
const router = useRouter()

// ---------------------- 请求实例创建函数 ----------------------
const createRequestInstance = (baseURL) => {
  const instance = axios.create({
    baseURL,
    timeout: 8000,
    headers: {
      "Content-Type": "application/json;charset=utf-8",
      Authorization: `Bearer ${localStorage.getItem("token") || ""}`
    }
  })

  // 请求拦截器
  instance.interceptors.request.use(config => {
    const token = localStorage.getItem("token")
    if (token) config.headers.Authorization = `Bearer ${token}`
    return config
  }, error => {
    ElMessage.error("请求参数错误，请检查输入")
    return Promise.reject(error)
  })

  // 响应拦截器
  instance.interceptors.response.use(
      response => response.data,
      error => {
        let errorMsg = "请求失败，请重试"
        if (error.response) {
          errorMsg = error.response.status === 401
              ? "登录已过期，请重新登录"
              : error.response.data?.msg || `请求失败（${error.response.status}）`
          if (error.response.status === 401) {
            localStorage.removeItem("token")
            router.push("/login")
          }
        } else if (error.code === "ECONNABORTED") {
          errorMsg = "请求超时，请检查后端服务"
        }
        ElMessage.error(errorMsg)
        return Promise.reject(error)
      }
  )
  return instance
}

// 初始化特定服务的请求实例（根据实际后端地址配置）
const rejectionAxios = createRequestInstance("http://localhost:9000") // 拒赔服务接口

// ---------------------- 视图状态与核心数据 ----------------------
// 当前视图（list：拒赔列表，review：审核详情）
const currentView = ref('list')
// 当前选中的拒赔记录
const currentRejection = reactive({})
// 多维度关联数据（通过报案号获取）
const reportInfo = reactive({}) // 报案信息
const policyInfo = reactive({}) // 保单信息
const registrationInfo = reactive({}) // 立案信息
const verificationInfo = reactive({}) // 核赔信息
// 下拉选项数据
const rejectionList = ref([]) // 拒赔列表数据
const reviewerOptions = ref([]) // 审核人员列表
// 分页与加载状态
const loading = ref(false)
const submitLoading = ref(false)
const verificationLoading = ref(false) // 核赔信息加载状态
const pageNum = ref(1)
const pageSize = ref(5)
const total = ref(0)
// 折叠面板状态（默认展开拒赔信息）
const activePanels = ref(["rejection"])
// 错误信息
const errorMsg = ref("")
const reviewFormRef = ref(null)  // 表单引用，用于验证和重置

// ---------------------- 筛选与审核表单 ----------------------
// 拒赔列表筛选表单
const filterForm = reactive({
  reportNo: '', // 报案编号
  rejectStatus: '' // 拒赔状态（1-待审核，2.已拒赔，3-审核未通过）
})

// 审核表单（提交给 /rejection/examineRejection 接口）
const reviewForm = reactive({
  rejectionId: '', // 拒赔ID（关联拒赔记录）
  rejectExamineId: '', // 审核人员ID
  rejectStatus: '2', // 审核结果（默认通过）
  examineReason: '' // 审核意见
})

// 审核表单验证规则
const reviewRules = reactive({
  rejectExamineId: [
    { required: true, message: "请选择审核人员", trigger: "change" }
  ],
  rejectStatus: [
    { required: true, message: "请选择审核结果", trigger: "change" }
  ],
  examineReason: [
    { required: true, message: "请填写审核意见", trigger: "blur" },
    { min: 15, message: "审核意见需至少15个字符", trigger: "blur" }
  ]
})

// ---------------------- 字典映射（统一状态与文本） ----------------------
// 拒赔状态映射
const rejectStatusMap = {
  "1": { text: '待审核', type: 'info', icon: Search },
  "2": { text: '已拒赔', type: 'danger', icon: Close },
  "3": { text: '审核未通过', type: 'warning', icon: Warning }
}

// 报案状态映射
const reportStatusMap = {
  "4": { text: '已立案', type: 'processing', icon: CheckCircle },
  "7": { text: '待结案', type: 'warning', icon: Warning },
  "10": { text: '拒赔申请中', type: 'danger', icon: Close }
}

// 灾祸类型映射
const disasterTypeMap = {
  '1': '暴雨', '2': '洪水', '3': '病虫害', '4': '疫病', '5': '其他'
}

// 责任认定映射
const liabilityMap = {
  "1": "属于保险责任", "0": "不属于保险责任", "": "未认定"
}

// 保单状态映射
const policyStatusMap = {
  "1": "待生效", "2": "已生效", "3": "已退保", "4": "已过期", "": "未知"
}

// 缴费状态映射
const payStatusMap = {
  "1": "待缴费", "2": "缴费中", "3": "缴费成功", "4": "缴费失败", "": "未知"
}

// ---------------------- 工具函数 ----------------------
/**
 * 格式化金额（保留2位小数）
 */
const formatCurrency = (value) => {
  if (!value && value !== 0) return "0.00"
  return Number(value).toFixed(2)
}

/**
 * 格式化日期时间（YYYY-MM-DD HH:mm:ss）
 */
const formatDateTime = (value) => {
  if (!value) return "未填写"
  return value.replace("T", " ").slice(0, 19)
}

/**
 * 格式化日期（YYYY-MM-DD）
 */
const formatDate = (value) => {
  if (!value) return "未填写"
  return value.split("T")[0] || "未填写"
}

/**
 * 获取灾祸类型文本
 */
const getDisasterType = (typeCode) => {
  return disasterTypeMap[typeCode] || "未知"
}

/**
 * 获取责任认定文本
 */
const getLiabilityType = (isCovered) => {
  return liabilityMap[isCovered?.toString()] || "未知"
}

/**
 * 获取保单状态文本
 */
const getPolicyStatus = (statusCode) => {
  return policyStatusMap[statusCode?.toString()] || "未知"
}

/**
 * 获取缴费状态文本
 */
const getPayStatus = (statusCode) => {
  return payStatusMap[statusCode?.toString()] || "未知"
}

/**
 * 判断是否有核赔数据
 */
const hasVerificationData = () => {
  return !!Object.keys(verificationInfo).length &&
      (!!verificationInfo.preClaimId || !!verificationInfo.verificationId)
}

// ---------------------- 拒赔列表相关方法 ----------------------
/**
 * 获取拒赔列表（调用 /rejection/RejectionList 接口）
 */
const getRejectionList = async () => {
  loading.value = true
  try {
    const res = await rejectionAxios.get("/rejection/RejectionList", {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        reportNo: filterForm.reportNo || undefined,
        rejectStatus: filterForm.rejectStatus || undefined
      }
    })

    if (res.code === 100200) {
      // 适配后端返回格式（假设 data 包含 list 和 total）
      rejectionList.value = res.data?.list || []
      total.value = res.data?.total || 0
      // 为每条记录添加审核加载状态
      rejectionList.value = rejectionList.value.map(item => ({
        ...item,
        reviewLoading: false
      }))
    } else {
      const errorMsg = res.msg || "获取拒赔列表失败"
      ElMessage.error(`获取拒赔列表失败：${errorMsg}`)
    }
  } catch (err) {
    const errorMsg = err.response?.data?.msg || err.message || "网络请求异常"
    ElMessage.error(`获取拒赔列表异常：${errorMsg}`)
  } finally {
    loading.value = false
  }
}

/**
 * 状态筛选变更（重置页码）
 */
const handleStatusChange = () => {
  pageNum.value = 1
  getRejectionList()
}

/**
 * 重置筛选条件
 */
const resetFilter = () => {
  filterForm.reportNo = ''
  filterForm.rejectStatus = ''
  pageNum.value = 1
  getRejectionList()
}

/**
 * 分页大小变更
 */
const handleSizeChange = (val) => {
  pageSize.value = val
  pageNum.value = 1
  getRejectionList()
}

/**
 * 当前页码变更
 */
const handleCurrentChange = (val) => {
  pageNum.value = val
  getRejectionList()
}

/**
 * 行点击事件（可选，点击行进入审核页）
 */
const handleRowClick = (row) => {
  toReviewPage(row)
}

/**
 * 跳转到审核详情页
 */
const toReviewPage = (row) => {
  currentView.value = 'review'
  // 赋值当前拒赔记录
  Object.assign(currentRejection, row)
  // 初始化审核表单
  reviewForm.rejectionId = row.rejectionId
  reviewForm.rejectExamineId = ''
  reviewForm.rejectStatus = '2'
  reviewForm.examineReason = ''
  // 加载关联数据（报案/保单/立案/核赔）
  initRelatedData(row.reportNo, row.preClaimId)
}

// ---------------------- 关联数据加载（通过报案号/核赔ID） ----------------------
/**
 * 初始化关联数据（报案+保单+立案+核赔）
 * @param {string} reportNo - 报案编号
 * @param {string} preClaimId - 核赔ID（可选）
 */
const initRelatedData = async (reportNo, preClaimId) => {
  // 重置关联数据
  Object.assign(reportInfo, {})
  Object.assign(policyInfo, {})
  Object.assign(registrationInfo, {})
  Object.assign(verificationInfo, {})

  if (!reportNo) {
    errorMsg.value = "缺少报案编号，无法加载关联数据"
    return
  }

  // 显示全局加载
  const loading = ElLoading.service({
    lock: true,
    text: "正在加载关联数据...",
    background: "rgba(255,255,255,0.7)"
  })

  try {
    // 1. 加载报案信息（核心关联字段）
    await fetchReportInfo(reportNo)

    // 2. 加载保单信息（通过报案信息中的 policyId）
    if (reportInfo.policyId) {
      await fetchPolicyInfo(reportInfo.policyId)
    }

    // 3. 加载立案信息（通过报案号）
    await fetchRegistrationInfo(reportNo)

    // 4. 加载核赔信息（优先用核赔ID，没有则尝试用报案号）
    if (preClaimId) {
      await fetchVerificationInfo(preClaimId)
    } else {
      await fetchVerificationByReportNo(reportNo)
    }

    // 5. 加载审核人员列表（PTN010：拒赔审核员职位编码，需与后端确认）
    await fetchReviewerList()

    // 展开所有面板
    activePanels.value = ["rejection", "report", "policy"]
    if (currentRejection.registrationId) activePanels.value.push("registration")
    if (hasVerificationData()) activePanels.value.push("verification")

  } finally {
    loading.close()
  }
}

/**
 * 获取报案详情（通过报案号）
 */
const fetchReportInfo = async (reportNo) => {
  try {
    const reportAxios = createRequestInstance("http://localhost:9000") // 报案服务地址
    const res = await reportAxios.get(`/aiClaimReport/${reportNo}`)
    if (res.code === 100200 && res.data) {
      Object.assign(reportInfo, res.data)
    } else {
      ElMessage.warning("未查询到报案信息")
    }
  } catch (error) {
    console.error("获取报案信息失败:", error)
    ElMessage.error("获取报案信息异常")
  }
}

/**
 * 获取保单详情（通过保单号）
 */
const fetchPolicyInfo = async (policyId) => {
  try {
    const res = await hxxp.get("/aiInsureOrder/getOrder", {
      params: { policyId }
    })
    if (res && res.policyId) {
      Object.assign(policyInfo, res)
    } else {
      ElMessage.warning(`未查询到保单号为${policyId}的信息`)
    }
  } catch (error) {
    console.error("获取保单信息失败:", error)
    ElMessage.error("获取保单信息异常")
  }
}

/**
 * 获取立案详情（通过报案号）
 */
const fetchRegistrationInfo = async (reportNo) => {
  try {
    const res = await hxxp.get(`/aiClaimRegistration/getByReportNo/${reportNo}`)
    if (res.code === 100200 && res.data) {
      Object.assign(registrationInfo, res.data)
    } else {
      ElMessage.warning("未查询到立案信息")
    }
  } catch (error) {
    console.error("获取立案信息失败:", error)
    ElMessage.error("获取立案信息异常")
  }
}

/**
 * 获取核赔详情（通过核赔ID）
 */
const fetchVerificationInfo = async (preClaimId) => {
  verificationLoading.value = true
  try {
    const res = await hxxp.get(`/aiClaimVerification/report`,{
      params: {preClaimId}
    })
    if (res.code === 100200 && res.data) {
      Object.assign(verificationInfo, res.data)
      return true
    } else {
      // 核赔ID查询失败时，尝试用报案号查询
      await fetchVerificationByReportNo(currentRejection.reportNo)
    }
  } catch (error) {
    console.error("获取核赔信息失败:", error)
    // 不显示错误提示，避免重复提示
  } finally {
    verificationLoading.value = false
  }
  return false
}

/**
 * 新增：通过报案号获取核赔信息
 */
const fetchVerificationByReportNo = async (reportNo) => {
  if (!reportNo) return false

  verificationLoading.value = true
  try {
    // 假设通过报案号查询核赔信息的接口，需与后端确认实际接口地址
    const res = await hxxp.get(`/aiClaimVerification/report`,{
      params: {reportNo}
    })
    if (res.code === 100200 && res.data) {
      Object.assign(verificationInfo, res.data)
      ElMessage.success("核赔信息加载成功")
      // 如果面板未展开，自动展开
      if (!activePanels.value.includes('verification')) {
        activePanels.value.push('verification')
      }
      return true
    } else {
      Object.assign(verificationInfo, {})
    }
  } catch (error) {
    console.error("通过报案号获取核赔信息失败:", error)
    ElMessage.error("加载核赔信息失败，请稍后重试")
  } finally {
    verificationLoading.value = false
  }
  return false
}

/**
 * 获取审核人员列表（PTN010：拒赔审核员职位编码）
 */
const fetchReviewerList = async () => {
  try {
    const res = await hxxp.get("/aiStaffUser/worker", {
      params: {
        positionCode: "PTN001" // 需与后端确认拒赔审核员的职位编码
      }
    })
    if (res.code === 100200) {
      reviewerOptions.value = (res.data || []).map(staff => ({
        workNo: staff.workNo || staff.work_no,
        realName: staff.realName || staff.real_name
      }))
      if (reviewerOptions.value.length === 0) {
        ElMessage.warning("当前无可用审核人员，请联系管理员配置")
      }
    } else {
      ElMessage.error(`获取审核人员列表失败：${res.msg || '未知错误'}`)
    }
  } catch (error) {
    console.error("获取审核人员列表失败:", error)
    ElMessage.error("获取审核人员列表异常")
  }
}

// ---------------------- 审核操作相关方法 ----------------------
/**
 * 审核结果变更（根据结果提示不同意见方向）
 */
const handleReviewResultChange = (value) => {
  if (value === '2') {
    reviewForm.examineReason = "拒赔原因充分，符合保险条款约定，同意拒赔申请。"
  } else if (value === '3') {
    reviewForm.examineReason = "拒赔原因不充分（或材料不全），不符合保险条款约定，驳回拒赔申请。"
  }
}

/**
 * 重置审核表单
 */
const handleResetReview = () => {
  if (reviewFormRef.value) {
    reviewFormRef.value.resetFields()
    reviewForm.rejectStatus = '2' // 重置为默认通过
  }
}

/**
 * 提交审核结果（调用 /rejection/examineRejection 接口）
 */
const handleSubmitReview = async () => {
  if (!reviewFormRef.value) return

  // 表单验证
  try {
    await reviewFormRef.value.validate()
  } catch (error) {
    ElMessage.error("表单验证失败，请检查标红字段")
    return
  }

  // 二次确认
  const confirmText = reviewForm.rejectStatus === '2'
      ? "确定通过审核并确认拒赔？此操作将更新拒赔状态为'已拒赔'！"
      : "确定驳回审核？此操作将更新拒赔状态为'审核未通过'！"

  ElMessageBox.confirm(
      confirmText,
      "审核确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: reviewForm.rejectStatus === '2' ? "danger" : "warning"
      }
  ).then(async () => {
    submitLoading.value = true
    const loading = ElLoading.service({
      lock: true,
      text: "正在提交审核结果...",
      background: "rgba(255,255,255,0.7)"
    })

    try {
      // 构造提交数据（与后端 Rejection 实体类匹配）
      const submitData = {
        rejectionId: reviewForm.rejectionId,
        rejectExamineId: reviewForm.rejectExamineId,
        rejectStatus: Number(reviewForm.rejectStatus),
        examineReason: reviewForm.examineReason,
      }

      // 调用审核接口
      const res = await rejectionAxios.put("/rejection/examineRejection", submitData)
      if (res.code === 100200) {
        ElMessage.success(res.msg || "审核结果提交成功！")
        // 返回列表并刷新
        switchToView('list')
      } else {
        ElMessage.error(`提交失败：${res.msg || '未知错误'}`)
      }
    } catch (error) {
      console.error("提交审核结果失败:", error)
      ElMessage.error(`提交审核结果异常：${error.message || '网络错误'}`)
    } finally {
      submitLoading.value = false
      loading.close()
    }
  }).catch(() => {
    ElMessage.info("已取消审核提交")
  })
}

// ---------------------- 视图切换方法 ----------------------
/**
 * 切换视图（列表/审核详情）
 */
const switchToView = (viewType) => {
  currentView.value = viewType
  if (viewType === 'list') {
    // 返回列表时刷新数据
    getRejectionList()
  }
}

// ---------------------- 页面初始化 ----------------------
onMounted(() => {
  // 初始加载拒赔列表
  getRejectionList()
})
</script>

<style scoped>
.rejection-review-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  background-color: #fafafa;
  min-height: calc(100vh - 120px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 筛选卡片样式 */
.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  margin-top: 15px;
}

/* 列表卡片样式 */
.list-card {
  min-height: 500px;
}

/* 详情卡片样式 */
.main-card {
  background-color: #fff;
  padding: 32px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

/* 折叠面板样式 */
.info-collapse {
  border: 1px solid #f1f3f4;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 24px;
}

.el-collapse-item__header {
  background-color: #f8f9fa;
  font-weight: 500;
}

.el-collapse-item__content {
  padding: 20px;
}

/* 高亮字段样式 */
.highlight-item {
  background-color: #f0f7ff;
  font-weight: 500;
}

/* 审核表单样式 */
.review-form .el-form-item {
  margin-bottom: 28px;
}

.review-form .el-form-item__help {
  margin-top: 4px;
}

.text-success {
  color: #198754;
}

.text-warning {
  color: #ffc107;
}

/* 操作按钮区域 */
.form-actions {
  margin-top: 40px;
  display: flex;
  justify-content: flex-end;
  gap: 16px;
}

/* 分页样式 */
.pagination {
  margin-top: 15px;
  text-align: right;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .rejection-review-container {
    padding: 16px;
  }

  .main-card {
    padding: 16px;
  }

  .el-collapse-item__content {
    padding: 12px;
  }

  .el-descriptions {
    column-count: 1 !important;
  }

  .form-actions {
    flex-direction: column;
    align-items: stretch;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>
